package edu.ynu.MyProject.service;
import edu.ynu.MyProject.common.service.LogicService;
import edu.ynu.MyProject.dao.ITokenDao;
import edu.ynu.MyProject.entity.TokenResponse;
import org.springframework.http.*;
import edu.ynu.MyProject.config.TokenConfig;
import edu.ynu.MyProject.entity.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


@Service
public class TokenService extends LogicService<ITokenDao, Token, Long> {
    private final TokenConfig tokenConfig;
    private final RestTemplate restTemplate;
    @Autowired
    private ITokenDao iTokenDao;

    @Autowired
    public TokenService(ITokenDao iTokenDao, RestTemplate restTemplate, TokenConfig tokenConfig) {
        super(iTokenDao);
        this.restTemplate = restTemplate;
        this.tokenConfig = tokenConfig;
    }

// 更新传感器token
    public String accessSensorToken() {
//        构造body
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("grant_type", tokenConfig.getGrant_type());
        body.add("client_id", tokenConfig.getClient_id());
        body.add("client_secret", tokenConfig.getClient_secret());
        body.add("scope", tokenConfig.getScope());
//        构造请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(body, headers);
        // 发送请求并接收
        ResponseEntity<TokenResponse> response = restTemplate.exchange(
                tokenConfig.getBase_url(),
                HttpMethod.POST,
                entity,
                TokenResponse.class
        );
        try {
            // 处理数据
            TokenResponse tokenResponse = response.getBody();
            Token token = new Token();
            token.setToken_type(tokenResponse.getToken_type());
            token.setToken(tokenResponse.getAccess_token());
            token.setScope(tokenResponse.getScope());
            token.setExpires_in(tokenResponse.getExpires_in());
//            存入数据库
            iTokenDao.save(token);
        }
        catch (RestClientException e) {
            // 处理 RestTemplate 相关异常
            System.err.println("Error during REST request: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            // 处理其他所有异常
            System.err.println("An unexpected error occurred: " + e.getMessage());
            e.printStackTrace();
        }
        return "Get sensor token ran";
    }

// 更新摄像头token
    public String accessCameraToken() {
//        构造body
        Map<String, String> body = new HashMap<>();
        body.put("accountId", tokenConfig.getAccount_id());

        // 构造请求头,设置 Content-Type为application/json
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, String>> entity = new HttpEntity<>(body, headers);

        try {
            // 发送请求并接收
            ResponseEntity<Map> response = restTemplate.exchange(
                    tokenConfig.getCamera_url(),
                    HttpMethod.POST,
                    entity,
                    Map.class);
            // 处理数据
            Map<String, Object> responseMap = response.getBody();
            Map<String, Object> dataMap = (Map<String, Object>) responseMap.get("data");

            Token token = new Token();
            token.setToken((String) dataMap.get("accessToken"));
            token.setScope("camera");
            token.setExpires_in((Long) dataMap.get("expireTime"));
    //       存入数据库
            iTokenDao.save(token);
        }
        catch (RestClientException e) {
            // 处理RestTemplate异常
            System.err.println("Error during REST request: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            // 其他异常
            System.err.println("An unexpected error occurred: " + e.getMessage());
            e.printStackTrace();
        }
        return "Get sensor token ran";
    }

// 获取传感器token
    public String getSensorToken() {
        Token token = iTokenDao.findTopByScopeOrderByCreateTimeDesc("fbox");
//        未获取到token或token已过期
        if (token == null || token.isExpired() ) {
            accessSensorToken();
            token = iTokenDao.findTopByScopeOrderByCreateTimeDesc("fbox");
        }
        return token.getToken();
    }

// 获取摄像头token
    public String getCameraToken() {
        Token token = iTokenDao.findTopByScopeOrderByCreateTimeDesc("camera");
//        未获取到token或token已过期
        if (token == null || token.isExpired() ) {
            accessCameraToken();
            token = iTokenDao.findTopByScopeOrderByCreateTimeDesc("camera");
        }
        return token.getToken();
    }
}
